package com.ukao.pad.printer;

import android.os.Handler;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gprinter.command.EscCommand;
import com.gprinterio.GpDevice;
import com.ukao.pad.bean.PrintAloneBean;
import com.ukao.pad.bean.ReceiptBean;
import com.ukao.pad.bean.StringBean;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.DateUtils;
import com.ukao.pad.utils.T;
import com.ukao.pad.utils.Utils;

import java.util.List;
import java.util.Vector;

/**
 * 打印小票
 */

public class PrinterReceipt {
    private int lengter = cutoff().length() - 7;
    private static PrinterReceipt mPrinterHelper;
    private Vector<Byte> Command;
    private List<PrintAloneBean.ProductListBean> productList;
    private EscCommand esc;
    private int productCount;
    private Handler   mHandler=new Handler();



    public static PrinterReceipt getInstance( ){
        if(mPrinterHelper == null) {
            mPrinterHelper = new PrinterReceipt();
        }
        return  mPrinterHelper;
    }


    /**
     * 下票打印机
     *
     * @return
     */
    //分割线
    public String cutoff() {
        String cutline = "------------------------------------------------\n";
        return cutline;
    }


    public String cutoffs() {
        String cutline = "________________________________________________\n";
        return cutline;
    }

    //对齐函数（用于一行打印信息一边左对齐一边右对齐）
    public String Align(String left, String right) {

        String str = left + "     " + right;
//        while(str.length() < lengter)
//        {
//            left = left;
//            str = left + right;
//
//        }

        return str;
    }

    public String AlignTwo(String left, String right) {

        String str = left + "     " + right;
        while (str.length() < lengter) {
            left = left + " ";
            str = left + right;

        }

        return str;
    }


    /**
     * 打印小票
     */
    public void printleaveFactory(final PrintAloneBean mPrintAloneBean, final GpDevice mDevice) {



        printBatch(mPrintAloneBean, mDevice);




    }

    private void printBatch(PrintAloneBean mPrintAloneBean, GpDevice mDevice)  {

        mDevice.openUSBPort(Utils.getContext());

        if (mDevice == null) {
            System.out.println("usbDevice is null");
            return;
        }

        try {


            esc = new EscCommand();

            PrintAloneBean.BatchBean mbatchBean = mPrintAloneBean.getBatch();

            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_2, EscCommand.HEIGHT_ZOOM.MUL_2);
            //设置居中
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            //打印字体
            esc.addText("出厂衣物小票" + "\n");
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_1, EscCommand.HEIGHT_ZOOM.MUL_1);
            esc.addPrintAndFeedLines((byte) 1);
            /*打印批次号*/
            esc.addSetBarcodeHeight((byte)120);
            esc.addSetBarcodeWidth((byte)3);
            esc.addCODE128(esc.genCodeB(mbatchBean.getCode())); // 打印Code128码
          //  esc.addRastBitImage(bitmap, bitmap.getWidth(), 0); // 打印图片
            esc.addPrintAndFeedLines((byte) 1);
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_2, EscCommand.HEIGHT_ZOOM.MUL_2);
            esc.addText(mbatchBean.getCode() + "\n");
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_1, EscCommand.HEIGHT_ZOOM.MUL_1);
            esc.addText(cutoffs());
            esc.addPrintAndFeedLines((byte) 1);
            if (!CheckUtils.isEmpty(mbatchBean.getFactoryName())&&!CheckUtils.isEmpty(mbatchBean.getStoreName())){
                esc.addText(mbatchBean.getFactoryName() + "   →     " + mbatchBean.getStoreName() + "\n");
                esc.addPrintAndFeedLines((byte) 1);
            }
            productList = mPrintAloneBean.getProductList();
            int count = mbatchBean.getProductCnt() + mbatchBean.getAnnexCnt();
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_2, EscCommand.HEIGHT_ZOOM.MUL_2);
            esc.addText("共" +count+ "件"+"\n");
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_1, EscCommand.HEIGHT_ZOOM.MUL_1);
            esc.addText("（衣物" + mbatchBean.getProductCnt() + "件，附件" + mbatchBean.getAnnexCnt() + "件)" + "\n"); /*衣物总数*/
            esc.addPrintAndFeedLines((byte) 1);
            esc.addText(cutoffs());
            esc.addPrintAndFeedLines((byte) 1);
            esc.addText("打印日期：" + DateUtils.getDateTime() + "\n");



//            if (!CheckUtils.isEmpty(productList)) {
//
//                        productCount = 0;
//                 printList(mDevice, count);
//                for (int i = 0; i < productList.size(); i++) {
//                    //打印条形码
//
//                     PrintAloneBean.ProductListBean productListBean = productList.get(i);
//                    esc.addSetBarcodeHeight((byte)35);
//                    esc.addCODE128(esc.genCodeB(productListBean.getScanCode())); // 打印Code128码
//                    esc.addText(Align(productListBean.getProductName(),productListBean.getScanCode())+"\n"); /*衣物与店铺*/
//                    if(i!=productList.size()-1) {
//                       // esc.addText(cutoff());
//
//                    }
//
//                }
//            } else {
//                sendDataImmediately(mDevice, count);
//            }


            if (mDevice.isDeviceOpen()){
                //切纸和切纸长度
                esc.addCutAndFeedPaper((byte) 20);
                Command = new Vector<Byte>(4096, 1024);
                Command = esc.getCommand();
                mDevice.sendDataImmediately(Command);
            }else{
                T.show("小票打印机USB连接失败，请重新拔插");
                return;
            }



        } catch (Exception ex) {
            System.out.println(ex.getStackTrace());
        }
    }

    private void sendDataImmediately(GpDevice mDevice, int count) {
        esc.addText(cutoffs());
        esc.addText("衣物总数：" + count + "\n");
        //切纸和切纸长度
        esc.addCutAndFeedPaper((byte) 20);

        Command = new Vector<Byte>(4096, 1024);
        Command = esc.getCommand();
        mDevice.sendDataImmediately(Command);
    }

    private void printList(final GpDevice mDevice, final int count) {
        if (productList.size()== productCount) {
            sendDataImmediately(mDevice, count);

        } else {
            final PrintAloneBean.ProductListBean productListBean = productList.get(productCount);
            productCount = productCount + 1;
            esc.addSetBarcodeHeight((byte)35);
            esc.addCODE128(esc.genCodeB(productListBean.getScanCode())); // 打印Code128码
            esc.addText(Align(productListBean.getProductName(), productListBean.getScanCode()) + "\n"); /*衣物与店铺*/
            if (productList.size()-1!= productCount) {
               // esc.addText(cutoff());

            }
            printList(mDevice, count);



        }

    }

    /**
     * 打印小票
     */
    public void printGp80(final ReceiptBean printInfo, final GpDevice mDevice) {
        PrintBarcode(printInfo, mDevice);

    }

    /**
     * 打印小票
     * @param printInfo
     * @param mDevice

     */
    private void PrintBarcode(ReceiptBean printInfo, GpDevice mDevice ) {

        mDevice.openUSBPort(Utils.getContext());
        if(mDevice == null){
            System.out.println("usbDevice is null");
            return;
        }

        try {



            EscCommand esc = new EscCommand();
            //设置字体
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_2,EscCommand.HEIGHT_ZOOM.MUL_2);
            //设置居中
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            //打印字体
            esc.addText(printInfo.getMercName() + "\n");
            if (!CheckUtils.isEmpty(printInfo.getStoreName())){
                esc.addText(printInfo.getStoreName() + "\n\n");
            }
            esc.addSetCharcterSize(EscCommand.WIDTH_ZOOM.MUL_1,EscCommand.HEIGHT_ZOOM.MUL_1);

            if (!CheckUtils.isEmpty(printInfo.getCabinetOrderNo())){
                esc.addText(printInfo.getCabinetOrderNo() + "\n");
            }
            if (!CheckUtils.isEmpty(printInfo.getCabinetName())){
                esc.addText(printInfo.getCabinetName() + "\n");
        }

            esc.addText(printInfo.getOrderNo()+"\n");


            //设置条形码高度  60   240
            esc.addSetBarcodeHeight((byte)120);
            //设置条形码宽度
            esc.addSetBarcodeWidth((byte)2);

            //打印条形码

            esc.addCODE128(esc.genCodeB(printInfo.getOrderNo()));

            //生成二维码，第一个参数为要生成的文本，第二个参数为生成尺寸，第三个参数为生成回调

            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
            List<ReceiptBean.OrderProductListBean> mProductList=printInfo.getOrderProductList();
            String    cloCount=printInfo.getClothCnt()+printInfo.getAnnexCnt();
            esc.addText(Align("入库 :" + DateUtils.formatDateCustom(printInfo.getRecoredTime(),"MM-dd HH:mm:ss"),cloCount +" \n"));

            String sendModeText=printInfo.getSendModeText();
            if (printInfo.getSendMode()==2&&!CheckUtils.isEmpty(printInfo.getSendWorkName())){
                sendModeText=sendModeText+":"+printInfo.getSendWorkName();

            }
            if (!CheckUtils.isEmpty(sendModeText)){
                esc.addText(sendModeText + "\n");
            }
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            esc.addText(cutoffs());
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);



            if (!CheckUtils.isEmpty(mProductList)){
                Gson mGson = new Gson();

                for (int j = 0; j < mProductList.size(); j++) {

                    ReceiptBean.OrderProductListBean orderProductListBean = mProductList.get(j);
                    String color="";
                    if (!CheckUtils.isEmpty(orderProductListBean.getColorDesc())) {  /*/*瑕疵*/
                        List<StringBean> mColorDesclist = mGson.fromJson(orderProductListBean.getColorDesc(),
                                new TypeToken<List<StringBean>>() {
                                }.getType());
                        StringBuffer mColorBuffer1 = new StringBuffer();
                        for (int i = 0; i < mColorDesclist.size(); i++) {
                            if (i != mColorDesclist.size() - 1) {
                                mColorBuffer1.append(mColorDesclist.get(i).getName() + "/");
                            } else {
                                mColorBuffer1.append(mColorDesclist.get(i).getName());
                            }


                        }
                        color= mColorBuffer1.toString();
                    }

                    String strflawDesc = "";
                    if (!CheckUtils.isEmpty(orderProductListBean.getFlawDesc())) {  /*/*瑕疵*/
                        List<StringBean> mflawDesclist = mGson.fromJson(orderProductListBean.getFlawDesc(),
                                new TypeToken<List<StringBean>>() {
                                }.getType());
                        StringBuffer mflawBuffer = new StringBuffer();
                        for (int i = 0; i < mflawDesclist.size(); i++) {
                            if (i != mflawDesclist.size() - 1) {
                                mflawBuffer.append(mflawDesclist.get(i).getName() + "/");
                            } else {
                                mflawBuffer.append(mflawDesclist.get(i).getName());
                            }


                        }
                        strflawDesc = mflawBuffer.toString();
                    }


                    esc.addText(Align(orderProductListBean.getProductName()+"  "+orderProductListBean.getScanCode(),"￥"+CheckUtils.isEmptyNumber(orderProductListBean.getSubtotal())+"\n"));/**/
                        //金额和输出线
                    esc.addText(Align("￥"+CheckUtils.isEmptyNumber(orderProductListBean.getServiceAmt())+"*"+orderProductListBean.getDiscount()+"%",orderProductListBean.getTranTypeStr()+" "+orderProductListBean.getTranNum()+"\n"));

                    if (!CheckUtils.isEmpty(color)&&!CheckUtils.isEmpty(strflawDesc)){
                        color=color+"/";

                    }
                    if (!CheckUtils.isEmpty(color)){
                        esc.addText(color+strflawDesc+"\n"); /*颜色*/
                    }

                    if(j == mProductList.size() - 1) {
                        //esc.addText(cutoffs());
                    }
                    else {
                        // esc.addText(cutoff());
                    }
                }
            }
            esc.addSelectJustification(EscCommand.JUSTIFICATION.RIGHT);
            if (!CheckUtils.isNull(printInfo.getPaymentPrice())){/*合计金额 */
                esc.addText("衣物总额："+CheckUtils.isEmptyNumber(printInfo.getOrderPrice())+"\n");
            }
            if (!CheckUtils.isNull(printInfo.getCouponAmt())&&printInfo.getCouponAmt()!=0){/*优惠卷 */
                esc.addText("优惠卷："+CheckUtils.isEmptyNumber(printInfo.getCouponAmt())+"\n");
            }
            if (printInfo.getIsModifyPrice()) {
                esc.addText("修改金额："+CheckUtils.isEmptyNumber(printInfo.getModifyPrice())+"\n");

            }

            int   takesEndFee=printInfo.getSendCarriage()+printInfo.getTakeCarriage();
            if (takesEndFee!=0){
                String    takesEndFees=CheckUtils.isEmptyNumber(takesEndFee);
                esc.addText("取送费："+takesEndFees+"\n");
            }

            if (printInfo.getPayStatus()){/* 已支付金额*/
                esc.addText("已付金额："+CheckUtils.isEmptyNumber(printInfo.getPaidPrice())+"\n");
            }

            esc.addText("付款状态："+printInfo.getPayStatusText()+"\n");
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            esc.addText(cutoff());
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);

            String    remark=printInfo.getUserRemark();
            if (!CheckUtils.isEmpty( remark)){
                esc.addText("客户备注："+remark+"\n");

            }else{
                esc.addText("客户备注：无"+"\n");
            }
            esc.addText(cutoff());
            String  userName="";
            if (!CheckUtils.isEmpty(printInfo.getUserName())){
                userName="  "+printInfo.getUserName();
            }
            if (!CheckUtils.isEmpty(printInfo.getUserPhone())){
                userName=printInfo.getUserPhone()+userName;
            }
            esc.addText("客户："+userName+"\n");
            esc.addText("卡号："+printInfo.getUserCardNo()+"\n");
           String  discount="";
            if (printInfo.getDiscountType()){
                discount="多折扣";
            }else{
                discount=printInfo.getDiscount()+"%";
            }
            esc.addText("折扣："+discount+"余额：￥"+CheckUtils.isEmptyNumber(printInfo.getUserBalance())+"\n");
            if (!CheckUtils.isEmpty(printInfo.getTakeAddress())){
                esc.addText(printInfo.getTakeAddress()+"\n");
            }
            esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
            esc.addText(cutoff());
            esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
            if (!CheckUtils.isEmpty(printInfo.getWxCode())){
                esc.addText("微信号："+printInfo.getWxCode()+"\n");
            }
            if (!CheckUtils.isEmpty(printInfo.getServiceTel())){
                esc.addText("客服电话："+printInfo.getServiceTel()+"\n");
            }

            esc.addText("打印时间："+DateUtils.getDateTime()+"\n");

            //切纸和切纸长度
            esc.addCutAndFeedPaper((byte)20);
            Vector<Byte> Command = new Vector<Byte>(4096, 1024);
            Command = esc.getCommand();
            if (mDevice.isDeviceOpen()){
                mDevice.sendDataImmediately(Command);
            }else{
                T.show("小票打印机USB连接失败，请重新拔插");
                return;
            }
        }catch (Exception ex){
            System.out.println(ex.getStackTrace());
        }
    }

}

